import 'dart:async';
import 'dart:convert' as convert;

import 'package:dio/dio.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:duo_zui/model/model.dart';
import 'package:duo_zui/router.dart';
import 'package:duo_zui/widget/common/common_snakeBar.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {

  String url;

  LoginPage({Key key, this.url}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  GlobalKey<ScaffoldState> registKey = new GlobalKey();

  TextEditingController _unameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  bool pwdShow = false;

  String _phoneNum = '';

  String _verifyCode = '';

  int _seconds = 0;

  String _verifyStr = '获取验证码';

  Timer _timer;

  int change = 1;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _cancelTimer();
  }

  _startTimer() {
    _seconds = 10;

    _timer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        return;
      }

      _seconds--;
      _verifyStr = '$_seconds(s)';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = '重新发送';
      }
    });
  }

  _cancelTimer() {
    _timer?.cancel();
  }

  Widget _buildCustomBar() {
    return new Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween, //子组件的排列方式为主轴两端对齐
      children: <Widget>[
        new InkWell(
          child: new Padding(
              padding: const EdgeInsets.all(12.0),
              child: new Icon(
                Icons.clear,
                size: 26.0,
                color: Colors.grey[700],
              )),
          onTap: () {
            //Navigator.pop(context);
            MyRouter.push(context, widget.url ,{'islogin':false,'myUser':new User()});
          },
        ),
        new InkWell(
          child: new Padding(
              padding: const EdgeInsets.all(12.0),
              child: new Text(
                "其他登录方式",
                style: new TextStyle(fontSize: 16.0, color: Colors.grey[700]),
              )),
          onTap: () {
            //showTips();
            setState(() {
              if(change == 1){
                change = 2;
              }else if(change == 2) {
                change = 1;
              }
            });
          },
        ),
      ],
    );
  }

  Widget _buildPhoneEdit() {
    var node = new FocusNode();
    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0),
      child: new TextField(
        onChanged: (str) {
          _phoneNum = str;
          setState(() {});
        },
        decoration: new InputDecoration(
          hintText: '请输入邮箱',
        ),
        //maxLines: 1,
        //maxLength: 11,
        //键盘展示为号码
        keyboardType: TextInputType.emailAddress,
        //只能输入数字
        // inputFormatters: <TextInputFormatter>[
        //   WhitelistingTextInputFormatter.digitsOnly,
        // ],
        onSubmitted: (text) {
          //FocusScope.of(context).reparentIfNeeded(node);
        },
      ),
    );
  }

  Widget _buildVerifyCodeEdit() {
    var node = new FocusNode();
    Widget verifyCodeEdit = new TextField(
      onChanged: (str) {
        _verifyCode = str;
        setState(() {});
      },
      decoration: new InputDecoration(
        hintText: '请输入短信验证码',
      ),
      maxLines: 1,
      maxLength: 6,
      //键盘展示为数字
      keyboardType: TextInputType.number,
      //只能输入数字
      inputFormatters: <TextInputFormatter>[
        WhitelistingTextInputFormatter.digitsOnly,
      ],
      onSubmitted: (text) {
        //FocusScope.of(context).reparentIfNeeded(node);
      },
    );

    Widget verifyCodeBtn = new InkWell(
      onTap: (_seconds == 0)
          ? () {
              setState(() {
                _startTimer();
              });
            }
          : null,
      child: new Container(
        alignment: Alignment.center,
        width: 100.0,
        height: 36.0,
        decoration: new BoxDecoration(
          border: new Border.all(
            width: 1.0,
            color: Colors.blue,
          ),
        ),
        child: new Text(
          '$_verifyStr',
          style: new TextStyle(fontSize: 14.0),
        ),
      ),
    );

    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
      child: new Stack(
        children: <Widget>[
          verifyCodeEdit,
          new Align(
            alignment: Alignment.topRight,
            child: verifyCodeBtn,
          ),
        ],
      ),
    );
  }

  //密码登录
  Widget _buildPasswordEdit() {
    var node = new FocusNode();
    Widget verifyCodeEdit = new TextField(
      onChanged: (str) {
        _verifyCode = str;
        setState(() {});
      },
      decoration: new InputDecoration(
        hintText: '请输入密码',
      ),
      obscureText: true,
      onSubmitted: (text) {
        //FocusScope.of(context).reparentIfNeeded(node);
      },
    );

    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
      child: new Stack(
        children: <Widget>[
          verifyCodeEdit
        ],
      ),
    );
  }

  Widget _buildLabel() {
    return new Container(
      margin: const EdgeInsets.only(top: 40.0, bottom: 20.0),
      alignment: Alignment.center,
      child: new Text(
        "登录嘟嘴APP，体验更多功能",
        style: new TextStyle(fontSize: 24.0),
      ),
    );
  }

  Widget _buildRegist() {
    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0, top: 20.0),
      child: new RaisedButton(
        color: Colors.blue,
        textColor: Colors.white,
        disabledColor: Colors.blue[100],
        onPressed: (_phoneNum.isEmpty || _verifyCode.isEmpty) ? null : () {
          getData('http://www.appshuo.club/api/login', _phoneNum, _verifyCode);
        },
        child: new Text(
          "登  录",
          style: new TextStyle(fontSize: 16.0),
        ),
      ),
    );
  }

  void getData(url,username,password) async{
    Dio dio = new Dio();
    Response response = await dio.post("$url",data: {'username':username, 'password': password});
    LoginResponse reslut = LoginResponse.fromJson(response.data);
    if(reslut.code != 200){
      return;//如果没有数据就不继续了
    }
    String userUrl = 'http://www.appshuo.club/api/user/info?accessToken=';
    _setData(userUrl,reslut.data);
  }

  _setData(url,String value) async {
    Dio dio = new Dio();
    Response response = await dio.get("$url$value");
    LoginResponse reslut = LoginResponse.fromJson(response.data);
    if(reslut.code != 200){
      return;//如果没有数据就不继续了
    }
    LoginUser user = LoginUser.fromJson(reslut.data);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(CacheKey.User_CACHE,convert.jsonEncode(user.user));
    prefs.setBool(CacheKey.USER_IS_LOGIN, user.islogin);
    prefs.setString(CacheKey.USE_NET_DATA, value);
    MyRouter.push(context, MyRouter.personDetailPage,{'islogin': user.islogin, 'myUser': user.user});
  }

  Widget _buildTips() {
    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0, top: 20.0),
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween, //子组件的排列方式为主轴两端对齐
        children: <Widget>[
          new Text(
            "未注册手机验证后自动登录",
            style: new TextStyle(fontSize: 14.0, color: Colors.grey[500]),
          ),
          new Text(
            "需要帮助",
            style: new TextStyle(fontSize: 14.0, color: Colors.blue),
          ),
        ],
      ),
    );
  }

  Widget _buildThirdPartLogin() {
    return new Row(
      mainAxisAlignment: MainAxisAlignment.center,
      // children: menus_login.map((Menu m) {
      //   return new GestureDetector(
      //     onTap: () {
      //       switch (m.index) {
      //         case 0:
      //           CommonSnakeBar.buildSnakeBarByKey(registKey, context, '点击了微信');
      //           break;
      //         case 1:
      //           CommonSnakeBar.buildSnakeBarByKey(
      //               registKey, context, '点击了新浪微博');
      //           break;
      //       }
      //     },
      //     child: new Padding(
      //         padding: const EdgeInsets.only(
      //             left: 24.0, top: 60.0, bottom: 12.0, right: 24.0),
      //         child: new Image.asset(
      //           m.icon,
      //           width: 60.0,
      //           height: 60.0,
      //         )),
      //   );
      // }).toList(),
    );
  }

  Widget _buildProtocol() {
    return new Padding(
      padding: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0,bottom: 20.0),
      child: new Container(
        child: new Text.rich(
          new TextSpan(
              text: '注册嘟嘴APP代表你已阅读并同意 ',
              style: new TextStyle(
                  fontSize: 14.0,
                  color: Colors.grey[500],
                  fontWeight: FontWeight.w400),
              children: [
                new TextSpan(
                    recognizer: new TapGestureRecognizer()
                      ..onTap = () {
                        CommonSnakeBar.buildSnakeBarByKey(
                            registKey, context, '点击了嘟嘴协议');
                      },
                    text: '嘟嘴协议',
                    style: new TextStyle(
                      fontSize: 14.0,
                      color: Colors.blue,
                      fontWeight: FontWeight.w400,
                    )),
                new TextSpan(
                    text: ' 和 ',
                    style: new TextStyle(
                      fontSize: 14.0,
                      color: Colors.grey[500],
                      fontWeight: FontWeight.w400,
                    )),
                new TextSpan(
                    recognizer: new TapGestureRecognizer()
                      ..onTap = () {
                        CommonSnakeBar.buildSnakeBarByKey(
                            registKey, context, '点击了隐私政策');
                      },
                    text: '隐私政策',
                    style: new TextStyle(
                      fontSize: 14.0,
                      color: Colors.blue,
                      fontWeight: FontWeight.w400,
                    )),
              ]),
        ),
      ),
    );
  }

  Widget _buildBody(){
    return new ListView(
      children: <Widget>[
        _buildCustomBar(),
        _buildLabel(),
        _buildPhoneEdit(),
        _buildPasswordEdit(),
        //_buildVerifyCodeEdit(),
        _buildRegist(),
        _buildTips(),
        _buildThirdPartLogin(),
        _buildProtocol(),
      ],
    );
  }

  Widget _build2Body(){
    return new ListView(
      children: <Widget>[
        _buildCustomBar(),
        _buildLabel(),
        _buildPhoneEdit(),
        //_buildPasswordEdit(),
        _buildVerifyCodeEdit(),
        _buildRegist(),
        _buildTips(),
        _buildThirdPartLogin(),
        _buildProtocol(),
      ],
    );
  }


  showTips() {
    showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return new Container(
              child: new Padding(
                  padding: const EdgeInsets.all(32.0),
                  child: new Text('没有相关接口，这是一个纯UI界面，提供部分交互体验',
                      textAlign: TextAlign.center,
                      style: new TextStyle(
                          color: Theme.of(context).accentColor,
                          fontSize: 24.0))));
        });
  }

  Widget _changeLogin(){
    if(change == 1){
      return _buildBody();
    }else{
      return _build2Body();
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new Scaffold(
        key: registKey,
        backgroundColor: Colors.white,
        body: _changeLogin(),
      ),
    );
  }
}

